local Piece = require "packages.chess-games.xiangqi.core.piece"

local King = Piece:subclass("Xiangqi.King")

function King:initialize(id)
  Piece.initialize(self, id)

  self.name = 'king'
  self.redStr = '帅'
  self.blackStr = '将'
end

---@param board integer[][]
---@param fromX integer
---@param fromY integer
---@param x integer
---@param y integer
function King:canMoveTo(board, fromX, fromY, x, y)
  local dx = x - fromX
  local dy = y - fromY

  -- 优先检查“将帅对面”
  -- 若x, y是对方将帅且中间无棋子 则可走
  local myColor = self:getColor()
  if x == fromX and board[y][x] + self.id == 0 then
    local step = (myColor == "red") and -1 or 1
    local scanY = fromY + step
    while scanY >= 1 and scanY <= 10 do
      local pieceId = board[scanY][x]
      if pieceId ~= 0 then
        if scanY == y then
          return true
        else
          break
        end
      end
      scanY = scanY + step
    end
  end

  -- 必须上下左右走一步
  if not ((math.abs(dx) == 1 and dy == 0) or (math.abs(dy) == 1 and dx == 0)) then
    return false
  end


  -- 必须在九宫格内
  if myColor == "red" then
    if x < 4 or x > 6 or y < 8 or y > 10 then
      return false
    end
  else
    if x < 4 or x > 6 or y < 1 or y > 3 then
      return false
    end
  end

  -- 目标位置若有己方棋子，不可走
  local targetId = board[y][x]
  if targetId ~= 0 then
    local targetColor = (targetId > 0) and "red" or "black"
    if myColor == targetColor then
      return false
    end
  end

  return true
end

return King

